package com.tuanzi.loan.core.util;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Ray 2017/10/24
 */
@Slf4j
public class JacksonUtils {

	public static final String toJson(Object object) {
		try {
			return getObjectMapper().writeValueAsString(object);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return StringUtils.EMPTY;
	}

	public static final <T> T toObject(String json, Class<T> cls) {
		try {
			return getObjectMapper().readValue(json, cls);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	private static ObjectMapper getObjectMapper() {
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
		objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, false);
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
			@Override
			public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
				gen.writeString("");
			}
		});
		return objectMapper;
	}

}
